package com.keyboardr.gamerater;

import java.util.ArrayList;

import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

public class GameAdapter extends BaseAdapter {

	private ArrayList<Game> games;
	private final RaterActivity mOwner;
	private final LayoutInflater mInflater;
	private Player filter;

	public GameAdapter(RaterActivity owner, Player player) {
		super();

		mInflater = owner.getLayoutInflater();
		mOwner = owner;
		setGameFilter(player);
	}

	public void setGameFilter(Player player) {
		filter = player;
		games = new ArrayList<Game>();
		if (player == null) {
			games = mOwner.getSelectedGroup().getGames();
		} else {
			for (Game game : mOwner.getSelectedGroup().getGames()) {
				if (player.equals(game.winner) || player.equals(game.loser)) {
					games.add(game);
				}
			}
		}
		super.notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		return games.size();
	}

	@Override
	public Object getItem(int position) {
		return games.get(games.size() - position - 1);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LinearLayout itemLayout;
		Game game = (Game) getItem(position);

		itemLayout = (LinearLayout) mInflater.inflate(R.layout.game_list_item,
				parent, false);
		((TextView) itemLayout.findViewById(R.id.gameDate)).setText(DateFormat
				.getDateFormat(mOwner).format(game.time));
		((TextView) itemLayout.findViewById(R.id.gameWinnerName))
				.setText(game.winner.toString());
		((TextView) itemLayout.findViewById(R.id.gameWinnerRating)).setText(""
				+ game.getWinRating());
		((TextView) itemLayout.findViewById(R.id.gameResult))
				.setText(game.draw ? R.string.draw : R.string.beat);
		((TextView) itemLayout.findViewById(R.id.gameLoserName))
				.setText(game.loser.toString());
		((TextView) itemLayout.findViewById(R.id.gameLoserRating)).setText(""
				+ game.getLoseRating());

		return itemLayout;
	}

	@Override
	public void notifyDataSetChanged() {
		setGameFilter(filter);
	}

}
